/**
 * @file STL_MysqlConnPool.h
 * @author Derek Liu (yjkhtddx@sina.com)
 * @brief 
 * @version 0.1
 * @date 2020-10-14
 * 
 * @copyright Copyright Sci-Tech Laboratories (c) 2020
 * 
 */

#ifndef _STL_MYSQL_CONN_POOL_H_
#define _STL_MYSQL_CONN_POOL_H_

#include <mysql/mysql.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <map>
#include <string>
#include <mutex>
#include <vector>
#include "STL_Json.h"
#include "STL_MysqlConnection.h"
#include "STL_Timestamp.h"

namespace STL
{
    class STL_MysqlConnPool
    {
    public:
        typedef struct Connection_t
        {
            STL_MysqlConnection *conn;
            bool isWork;
            long createAt;
            long lastWork;
            Connection_t(STL_MysqlConnection *conn)
            {
                this->conn = conn;
                this->isWork = false;
                this->createAt = getTimestamp();
                this->lastWork = this->createAt;
            }
        } Connection;

    private:
        STL_MysqlConnPool();
        ~STL_MysqlConnPool();

    public:
        static int initPool(std::string host, unsigned int port, std::string user, std::string passwd, std::string database, int poolSize);
        static void destroyPool();

    public:
        static std::mutex s_poolMutex;
        static std::mutex s_execMutex;
        static std::mutex s_initMutex;
        static std::mutex s_logMutex;

    private: // 配置
        static STL_MysqlConnPool *s_instance;
        static std::string s_host;
        static unsigned int s_port;
        static std::string s_user;
        static std::string s_password;
        static std::string s_database;
        static long s_maxlifetime;
        static long s_idleTimeout;
        static int s_maxPoolSize;

    public:
        static STL_MysqlConnPool *getInstance()
        {
            return s_instance;
        };

    public:
        static STL_MysqlConnection *getConnection(int index = -1);
        static int releaseConnection(STL_MysqlConnection *);

    public:
        static std::string genSql(std::string sql, JSONCPP::Value j_array);

    private:
        STL_MysqlSome *vec; // need an instance to init
    };
} // namespace STL
#endif // _STL_MYSQL_CONN_POOL_H_